#include "native_camera_manager.h"
#include <android/log.h>
#include <android/trace.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cstring>

NativeCameraManager::NativeCameraManager() 
    : cameraManager(nullptr)
    , cameraDevice(nullptr)
    , captureSession(nullptr)
    , previewRequest(nullptr)
    , previewTarget(nullptr)
    , previewSurface(nullptr)
    , imageReader(nullptr)
    , currentCameraId("")
    , currentPhotoFilename("")
    , isPreviewActive(false) {
}

void NativeCameraManager::onImageAvailable(void* context, AImageReader* reader) {
    ATrace_beginSection("NativeCameraManager::onImageAvailable");
    
    if (!context) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onImageAvailable: Invalid context");
        ATrace_endSection();
        return;
    }
    
    AImage* image = nullptr;
    media_status_t status = AImageReader_acquireLatestImage(reader, &image);
    if (status != AMEDIA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onImageAvailable: Failed to acquire image");
        ATrace_endSection();
        return;
    }
    
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "onImageAvailable: Image acquired successfully");
    
    // 获取图像平面信息
    int32_t numPlanes = 0;
    status = AImage_getNumberOfPlanes(image, &numPlanes);
    if (status != AMEDIA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onImageAvailable: Failed to get number of planes");
        AImage_delete(image);
        ATrace_endSection();
        return;
    }
    
    // 获取第一个平面的数据
    uint8_t* data = nullptr;
    int dataLength = 0;
    status = AImage_getPlaneData(image, 0, &data, &dataLength);
    if (status != AMEDIA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onImageAvailable: Failed to get plane data");
        AImage_delete(image);
        ATrace_endSection();
        return;
    }
    
    // 保存图像到文件
    ATrace_beginSection("SAVE_IMAGE_TO_FILE");
    NativeCameraManager* manager = static_cast<NativeCameraManager*>(context);
    if (!manager->currentPhotoFilename.empty()) {
        const std::string& fullPath = manager->currentPhotoFilename;
        int fd = open(fullPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (fd >= 0) {
            ssize_t written = write(fd, data, dataLength);
            close(fd);
            if (written == dataLength) {
                __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "onImageAvailable: Image saved successfully to %s", fullPath.c_str());
            } else {
                __android_log_print(ANDROID_LOG_WARN, "NativeCamera", "onImageAvailable: Image partially saved to %s", fullPath.c_str());
            }
        } else {
            __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onImageAvailable: Failed to save image to %s", fullPath.c_str());
        }
    }
    ATrace_endSection();
    
    // 清理资源
    AImage_delete(image);
    ATrace_endSection();
}

NativeCameraManager::~NativeCameraManager() {
    closeCamera();
    if (cameraManager) {
        ACameraManager_delete(cameraManager);
    }
}

bool NativeCameraManager::initialize() {
    ATrace_beginSection("NativeCameraManager::initialize");
    
    cameraManager = ACameraManager_create();
    if (!cameraManager) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "initialize: Failed to create camera manager");
        ATrace_endSection();
        return false;
    }
    
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "initialize: Camera manager created successfully");
    ATrace_endSection();
    return true;
}

std::vector<std::string> NativeCameraManager::getAvailableCameras() {
    ATrace_beginSection("NativeCameraManager::getAvailableCameras");
    std::vector<std::string> cameras;
    
    if (!cameraManager) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "getAvailableCameras: Camera manager not initialized");
        ATrace_endSection();
        return cameras;
    }
    
    ATrace_beginSection("GET_CAMERA_ID_LIST");
    ACameraIdList* cameraIdList = nullptr;
    camera_status_t status = ACameraManager_getCameraIdList(cameraManager, &cameraIdList);
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "getAvailableCameras: Failed to get camera list");
        ATrace_endSection();
        return cameras;
    }
    ATrace_endSection();
    
    ATrace_beginSection("PROCESS_CAMERA_LIST");
    for (int i = 0; i < cameraIdList->numCameras; i++) {
        cameras.push_back(std::string(cameraIdList->cameraIds[i]));
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "getAvailableCameras: Found camera %s", cameraIdList->cameraIds[i]);
    }
    ATrace_endSection();
    
    ATrace_beginSection("CLEANUP_CAMERA_LIST");
    ACameraManager_deleteCameraIdList(cameraIdList);
    ATrace_endSection();
    
    ATrace_endSection();
    return cameras;
}

bool NativeCameraManager::openCamera(const std::string& cameraId) {
    ATrace_beginSection("NativeCameraManager::openCamera");
    
    if (!cameraManager) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "openCamera: Camera manager not initialized");
        ATrace_endSection();
        return false;
    }
    
    if (cameraDevice) {
        __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "openCamera: Closing current camera before opening new one");
        closeCamera();
    }
    
    // 设置设备状态回调
    ATrace_beginSection("SETUP_DEVICE_CALLBACKS");
    ACameraDevice_StateCallbacks deviceCallbacks = {
        .context = this,
        .onDisconnected = onDeviceDisconnected,
        .onError = onDeviceError,
    };
    ATrace_endSection();
    
    ATrace_beginSection("OPEN_CAMERA_DEVICE");
    camera_status_t status = ACameraManager_openCamera(
        cameraManager, 
        cameraId.c_str(), 
        &deviceCallbacks, 
        &cameraDevice
    );
    
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "openCamera: Failed to open camera device, status: %d", status);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    currentCameraId = cameraId;
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "openCamera: Camera opened successfully");
    ATrace_endSection();
    return true;
}

void NativeCameraManager::closeCamera() {
    ATrace_beginSection("NativeCameraManager::closeCamera");
    
    ATrace_beginSection("STOP_PREVIEW");
    stopPreview();
    ATrace_endSection();
    
    // 清理捕获会话
    ATrace_beginSection("CLEANUP_CAPTURE_SESSION");
    cleanupCaptureSession();
    ATrace_endSection();
    
    if (imageReader) {
        ATrace_beginSection("DELETE_IMAGE_READER");
        AImageReader_delete(imageReader);
        imageReader = nullptr;
        ATrace_endSection();
    }
    
    if (cameraDevice) {
        ATrace_beginSection("CLOSE_CAMERA_DEVICE");
        ACameraDevice_close(cameraDevice);
        cameraDevice = nullptr;
        ATrace_endSection();
    }
    
    currentCameraId.clear();
    ATrace_endSection();
}

bool NativeCameraManager::startPreview(ANativeWindow* surface) {
    ATrace_beginSection("NativeCameraManager::startPreview");
    
    if (!cameraDevice) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Camera device not opened");
        ATrace_endSection();
        return false;
    }
    
    if (isPreviewActive) {
        __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "startPreview: Preview already active");
        ATrace_endSection();
        return true;
    }
    
    if (!surface) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Input surface is null");
        ATrace_endSection();
        return false;
    }
    
    ATrace_beginSection("SET_PREVIEW_SURFACE");
    previewSurface = surface;
    ATrace_endSection();
    
    // 检查Surface的有效性
    int32_t width = ANativeWindow_getWidth(surface);
    int32_t height = ANativeWindow_getHeight(surface);
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "startPreview: Surface dimensions: %dx%d", width, height);
    
    // 设置预览Surface格式
    ATrace_beginSection("SET_SURFACE_FORMAT");
    int32_t formatResult = ANativeWindow_setBuffersGeometry(surface, 0, 0, WINDOW_FORMAT_RGBA_8888);
    if (formatResult != 0) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to set surface format: %d", formatResult);
    }
    ATrace_endSection();
    
    // 创建ImageReader用于拍照
    ATrace_beginSection("CREATE_IMAGE_READER");
    
    // 清理之前的ImageReader
    if (imageReader) {
        AImageReader_delete(imageReader);
        imageReader = nullptr;
    }
    
    // 创建新的ImageReader，使用JPEG格式，最大图像数为4
    media_status_t readerStatus = AImageReader_new(1920, 1080, AIMAGE_FORMAT_JPEG, 4, &imageReader);
    if (readerStatus != AMEDIA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to create ImageReader: %d", readerStatus);
        ATrace_endSection();
        return false;
    }
    
    // 设置ImageReader的图像可用监听器
    AImageReader_ImageListener listener = {
        .context = this,
        .onImageAvailable = onImageAvailable
    };
    AImageReader_setImageListener(imageReader, &listener);
    ATrace_endSection();
    
    // 创建捕获会话
    ATrace_beginSection("CREATE_CAPTURE_SESSION");
    
    // 获取ImageReader的Surface用于拍照
    ANativeWindow* imageWindow = nullptr;
    if (imageReader) {
        media_status_t status = AImageReader_getWindow(imageReader, &imageWindow);
        if (status != AMEDIA_OK) {
            __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to get ImageReader window: %d", status);
            ATrace_endSection();
            return false;
        }
    }
    
    // 创建包含预览Surface和ImageReader Surface的会话
    std::vector<ANativeWindow*> surfaces = {previewSurface};
    if (imageWindow) {
        surfaces.push_back(imageWindow);
    }
    
    if (!createCaptureSession(surfaces)) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to create capture session");
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 创建预览捕获请求
    ATrace_beginSection("CREATE_PREVIEW_REQUEST");
    camera_status_t status = ACameraDevice_createCaptureRequest(cameraDevice, TEMPLATE_PREVIEW, &previewRequest);
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to create preview capture request: %d", status);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 为预览创建输出目标
    ATrace_beginSection("CREATE_PREVIEW_TARGET");
    if (!previewSurface) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Preview surface is null pointer");
        ATrace_endSection();
        return false;
    }
    
    status = ACameraOutputTarget_create(previewSurface, &previewTarget);
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to create preview output target: %d", status);
        if (previewRequest) {
            ACaptureRequest_free(previewRequest);
            previewRequest = nullptr;
        }
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 添加预览目标到请求
    ATrace_beginSection("ADD_PREVIEW_TARGET");
    status = ACaptureRequest_addTarget(previewRequest, previewTarget);
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to add preview target to request: %d", status);
        if (previewTarget) {
            ACameraOutputTarget_free(previewTarget);
            previewTarget = nullptr;
        }
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 如果会话已经准备好，立即启动预览
    if (captureSession) {
        // 立即启动重复捕获请求
        ATrace_beginSection("START_REPEATING_REQUEST");
        
        // 设置捕获回调以监控每一帧
        ACameraCaptureSession_captureCallbacks captureCallbacks = {
            .context = this,
            .onCaptureStarted = onCaptureStarted,
            .onCaptureProgressed = onCaptureProgressed,
            .onCaptureCompleted = onCaptureCompleted,
            .onCaptureFailed = onCaptureFailed,
            .onCaptureSequenceCompleted = nullptr,
            .onCaptureSequenceAborted = nullptr,
            .onCaptureBufferLost = nullptr
        };
        
        status = ACameraCaptureSession_setRepeatingRequest(captureSession, &captureCallbacks, 1, &previewRequest, nullptr);
        if (status == ACAMERA_OK) {
            isPreviewActive = true;
            __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "startPreview: Preview started successfully with frame callbacks");
        } else {
            __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "startPreview: Failed to start preview immediately, status: %d", status);
        }
        ATrace_endSection();
    }
    
    ATrace_endSection();
    return true;
}

void NativeCameraManager::stopPreview() {
    ATrace_beginSection("NativeCameraManager::stopPreview");
    
    if (!isPreviewActive) {
        ATrace_endSection();
        return;
    }
    
    // 停止重复请求但保持捕获会话活跃
    if (captureSession) {
        ATrace_beginSection("STOP_REPEATING");
        camera_status_t status = ACameraCaptureSession_stopRepeating(captureSession);
        if (status != ACAMERA_OK) {
            __android_log_print(ANDROID_LOG_WARN, "NativeCamera", "stopPreview: Failed to stop repeating: %d", status);
        }
        ATrace_endSection();
    }
    
    // 清理预览相关资源但保持捕获会话
    ATrace_beginSection("CLEANUP_PREVIEW_RESOURCES");
    if (previewRequest) {
        ACaptureRequest_free(previewRequest);
        previewRequest = nullptr;
    }
    
    if (previewTarget) {
        ACameraOutputTarget_free(previewTarget);
        previewTarget = nullptr;
    }
    
    if (previewSurface) {
        ANativeWindow_release(previewSurface);
        previewSurface = nullptr;
    }
    ATrace_endSection();
    
    isPreviewActive = false;
    
    ATrace_endSection();
}

bool NativeCameraManager::takePicture(const std::string& filename) {
    ATrace_beginSection("NativeCameraManager::takePicture");
    
    if (!cameraDevice || !captureSession) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "takePicture: Camera not ready - cameraDevice: %p, captureSession: %p", 
             cameraDevice, captureSession);
        ATrace_endSection();
        return false;
    }
    
    // 保存当前拍照文件名
    currentPhotoFilename = filename;
    
    // 检查ImageReader是否已创建
    if (!imageReader) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "takePicture: ImageReader not created");
        ATrace_endSection();
        return false;
    }
    
    // 获取ImageReader的Surface
    ATrace_beginSection("GET_IMAGE_WINDOW");
    ANativeWindow* imageWindow = nullptr;
    media_status_t status = AImageReader_getWindow(imageReader, &imageWindow);
    if (status != AMEDIA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "takePicture: Failed to get image window: %d", status);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 创建拍照输出目标
    ATrace_beginSection("CREATE_PHOTO_TARGET");
    ACameraOutputTarget* photoTarget = nullptr;
    camera_status_t cameraStatus = ACameraOutputTarget_create(imageWindow, &photoTarget);
    if (cameraStatus != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "takePicture: Failed to create photo target: %d", cameraStatus);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 创建拍照捕获请求
    ATrace_beginSection("CREATE_PHOTO_REQUEST");
    ACaptureRequest* photoRequest = nullptr;
    cameraStatus = ACameraDevice_createCaptureRequest(cameraDevice, TEMPLATE_STILL_CAPTURE, &photoRequest);
    if (cameraStatus != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "takePicture: Failed to create photo request: %d", cameraStatus);
        ACameraOutputTarget_free(photoTarget);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 设置拍照参数
    ATrace_beginSection("SET_PHOTO_PARAMETERS");
    uint8_t afMode = ACAMERA_CONTROL_AF_MODE_CONTINUOUS_PICTURE;
    ACaptureRequest_setEntry_u8(photoRequest, ACAMERA_CONTROL_AF_MODE, 1, &afMode);
    
    uint8_t aeMode = ACAMERA_CONTROL_AE_MODE_ON;
    ACaptureRequest_setEntry_u8(photoRequest, ACAMERA_CONTROL_AE_MODE, 1, &aeMode);
    
    uint8_t awbMode = ACAMERA_CONTROL_AWB_MODE_AUTO;
    ACaptureRequest_setEntry_u8(photoRequest, ACAMERA_CONTROL_AWB_MODE, 1, &awbMode);
    ATrace_endSection();
    
    // 添加拍照目标到请求
    ATrace_beginSection("ADD_PHOTO_TARGET");
    cameraStatus = ACaptureRequest_addTarget(photoRequest, photoTarget);
    if (cameraStatus != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "takePicture: Failed to add photo target: %d", cameraStatus);
        ACaptureRequest_free(photoRequest);
        ACameraOutputTarget_free(photoTarget);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 执行拍照捕获
    ATrace_beginSection("CAPTURE_PHOTO");
    
    // 设置拍照回调，使用专门的拍照回调函数
    ACameraCaptureSession_captureCallbacks photoCaptureCallbacks = {
        .context = this,
        .onCaptureStarted = onPhotoCaptureStarted,
        .onCaptureProgressed = onPhotoCaptureProgressed,
        .onCaptureCompleted = onPhotoCaptureCompleted,
        .onCaptureFailed = onPhotoCaptureFailed,
        .onCaptureSequenceCompleted = nullptr,
        .onCaptureSequenceAborted = nullptr,
        .onCaptureBufferLost = nullptr
    };
    
    cameraStatus = ACameraCaptureSession_capture(captureSession, &photoCaptureCallbacks, 1, &photoRequest, nullptr);
    if (cameraStatus != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "takePicture: Failed to capture photo: %d", cameraStatus);
        ACaptureRequest_free(photoRequest);
        ACameraOutputTarget_free(photoTarget);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 清理资源
    ATrace_beginSection("CLEANUP_PHOTO_RESOURCES");
    ACaptureRequest_free(photoRequest);
    ACameraOutputTarget_free(photoTarget);
    ATrace_endSection();
    
    ATrace_endSection();
    return true;
}

bool NativeCameraManager::createCaptureSession(const std::vector<ANativeWindow*>& surfaces) {
    ATrace_beginSection("NativeCameraManager::createCaptureSession");
    
    if (surfaces.empty()) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "createCaptureSession: Empty surfaces list");
        ATrace_endSection();
        return false;
    }
    
    // 创建输出容器
    ATrace_beginSection("CREATE_OUTPUT_CONTAINER");
    ACaptureSessionOutputContainer* outputContainer = nullptr;
    camera_status_t status = ACaptureSessionOutputContainer_create(&outputContainer);
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "createCaptureSession: Failed to create output container: %d", status);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    // 为每个Surface创建输出并添加到容器
    ATrace_beginSection("ADD_SURFACES_TO_CONTAINER");
    for (ANativeWindow* surface : surfaces) {
        ACaptureSessionOutput* output = nullptr;
        status = ACaptureSessionOutput_create(surface, &output);
        if (status != ACAMERA_OK) {
            __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "createCaptureSession: Failed to create output for surface: %d", status);
            ACaptureSessionOutputContainer_free(outputContainer);
            ATrace_endSection();
            return false;
        }
        
        status = ACaptureSessionOutputContainer_add(outputContainer, output);
        if (status != ACAMERA_OK) {
            __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "createCaptureSession: Failed to add output to container: %d", status);
            ACaptureSessionOutput_free(output);
            ACaptureSessionOutputContainer_free(outputContainer);
            ATrace_endSection();
            return false;
        }
        
        ACaptureSessionOutput_free(output);
    }
    ATrace_endSection();
    
    // 设置会话状态回调
    ATrace_beginSection("CREATE_SESSION");
    ACameraCaptureSession_stateCallbacks sessionCallbacks = {
        .context = this,
        .onClosed = onSessionClosed,
        .onReady = onSessionReady,
        .onActive = onSessionActive
    };
    
    status = ACameraDevice_createCaptureSession(cameraDevice, outputContainer, &sessionCallbacks, &captureSession);
    ACaptureSessionOutputContainer_free(outputContainer);
    
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "createCaptureSession: Failed to create capture session: %d", status);
        ATrace_endSection();
        return false;
    }
    ATrace_endSection();
    
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "createCaptureSession: Capture session created successfully");
    ATrace_endSection();
    return true;
}

void NativeCameraManager::onSessionReady(void* context, ACameraCaptureSession* session) {
    // 标记未使用的参数以避免编译警告
    (void)context;
    (void)session;
    
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "onSessionReady: Capture session is ready");
}

void NativeCameraManager::onSessionActive(void* context, ACameraCaptureSession* session) {
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "onSessionActive: Capture session is active");
    
    if (!context || !session) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onSessionActive: Invalid parameters");
        return;
    }
    
    NativeCameraManager* manager = static_cast<NativeCameraManager*>(context);
    
    // 会话激活后，可以开始捕获
    if (!manager->previewRequest || !manager->captureSession) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onSessionActive: Preview request or capture session is null");
        return;
    }
    
    ATrace_beginSection("START_REPEATING_REQUEST");
    
    // 设置捕获回调以监控每一帧
    ACameraCaptureSession_captureCallbacks captureCallbacks = {
        .context = manager,
        .onCaptureStarted = onCaptureStarted,
        .onCaptureProgressed = onCaptureProgressed,
        .onCaptureCompleted = onCaptureCompleted,
        .onCaptureFailed = onCaptureFailed,
        .onCaptureSequenceCompleted = nullptr,
        .onCaptureSequenceAborted = nullptr,
        .onCaptureBufferLost = nullptr
    };
    
    camera_status_t status = ACameraCaptureSession_setRepeatingRequest(
        manager->captureSession, &captureCallbacks, 1, &manager->previewRequest, nullptr);
    
    if (status != ACAMERA_OK) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "onSessionActive: Failed to start repeating request: %d", status);
        ATrace_endSection();
        return;
    }
    
    manager->isPreviewActive = true;
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "onSessionActive: Preview started successfully with frame callbacks");
    ATrace_endSection();
}

/**
 * 检查相机是否已打开
 * @return 相机是否已打开
 */
bool NativeCameraManager::isCameraOpen() const {
    return cameraDevice != nullptr;
}

void NativeCameraManager::cleanupCaptureSession() {
    ATrace_beginSection("NativeCameraManager::cleanupCaptureSession");
    
    // 清理捕获会话
    if (captureSession) {
        ACameraCaptureSession_close(captureSession);
        captureSession = nullptr;
    }
    
    ATrace_endSection();
}

void NativeCameraManager::onSessionClosed(void* context, ACameraCaptureSession* session) {
    (void)context;  // 标记未使用参数
    (void)session;  // 标记未使用参数
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "捕获会话关闭");
    // 处理会话关闭
}

void NativeCameraManager::onDeviceDisconnected(void* context, ACameraDevice* device) {
    (void)context;  // 标记未使用参数
    (void)device;   // 标记未使用参数
    __android_log_print(ANDROID_LOG_WARN, "NativeCamera", "相机设备断开连接");
    // 处理设备断开连接
}

void NativeCameraManager::onDeviceError(void* context, ACameraDevice* device, int error) {
    (void)context;  // 标记未使用参数
    (void)device;   // 标记未使用参数
    __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "相机设备错误: %d", error);
    // 处理设备错误
}

/**
 * 捕获开始回调 - 每一帧开始时调用
 */
void NativeCameraManager::onCaptureStarted(void* context, ACameraCaptureSession* session,
                                          const ACaptureRequest* request, int64_t timestamp) {
    (void)context;
    (void)session;
    (void)request;
    
    // 预览帧开始
    __android_log_print(ANDROID_LOG_VERBOSE, "NativeCamera", 
                       "Frame Started: timestamp=%lld", (long long)timestamp);
}

/**
 * 捕获进行中回调 - 每一帧处理过程中调用
 */
void NativeCameraManager::onCaptureProgressed(void* context, ACameraCaptureSession* session,
                                             ACaptureRequest* request, const ACameraMetadata* result) {
    (void)context;
    (void)session;
    (void)request;
    (void)result;
    
    // 预览帧处理中的日志 - 通常这个回调很少被调用
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "*** Frame Progressed *** (rarely called)");
}

/**
 * 捕获完成回调 - 每一帧完成时调用
 */
void NativeCameraManager::onCaptureCompleted(void* context, ACameraCaptureSession* session,
                                            ACaptureRequest* request, const ACameraMetadata* result) {
    (void)context;
    (void)session;
    (void)request;
    
    // 预览帧完成
    __android_log_print(ANDROID_LOG_DEBUG, "NativeCamera", "Frame Completed");
    
    // 可以在这里获取帧的元数据信息
    if (result) {
        // 示例：获取曝光时间
        ACameraMetadata_const_entry entry = {};
        camera_status_t status = ACameraMetadata_getConstEntry(result, 
                                                              ACAMERA_SENSOR_EXPOSURE_TIME, &entry);
        if (status == ACAMERA_OK && entry.count > 0) {
            int64_t exposureTime = entry.data.i64[0];
            __android_log_print(ANDROID_LOG_VERBOSE, "NativeCamera", 
                               "Frame Metadata - Exposure Time: %lld ns", (long long)exposureTime);
        }
    }
}

/**
 * 捕获失败回调 - 每一帧失败时调用
 */
void NativeCameraManager::onCaptureFailed(void* context, ACameraCaptureSession* session,
                                         ACaptureRequest* request, ACameraCaptureFailure* failure) {
    (void)context;
    (void)session;
    (void)request;
    
    if (failure) {
        __android_log_print(ANDROID_LOG_WARN, "NativeCamera", 
                           "Frame Failed - Reason: %d, Frame Number: %lld", 
                           failure->reason, (long long)failure->frameNumber);
    } else {
        __android_log_print(ANDROID_LOG_WARN, "NativeCamera", "Frame Failed - Unknown reason");
    }
}

// 专门的拍照回调函数
void NativeCameraManager::onPhotoCaptureStarted(void* context, ACameraCaptureSession* session,
                                               const ACaptureRequest* request, int64_t timestamp) {
    (void)context;
    (void)session;
    (void)request;
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", 
                       "📸 PHOTO Frame Started: timestamp=%lld", (long long)timestamp);
}

void NativeCameraManager::onPhotoCaptureProgressed(void* context, ACameraCaptureSession* session,
                                                  ACaptureRequest* request, const ACameraMetadata* partialResult) {
    (void)context;
    (void)session;
    (void)request;
    (void)partialResult;
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "📸 PHOTO Frame Progressed");
}

void NativeCameraManager::onPhotoCaptureCompleted(void* context, ACameraCaptureSession* session,
                                                 ACaptureRequest* request, const ACameraMetadata* result) {
    (void)context;
    (void)session;
    (void)request;
    __android_log_print(ANDROID_LOG_INFO, "NativeCamera", "📸 PHOTO Frame Completed");
    
    // 处理拍照元数据
    if (result) {
        ACameraMetadata_const_entry entry = {};
        camera_status_t status = ACameraMetadata_getConstEntry(result, ACAMERA_SENSOR_EXPOSURE_TIME, &entry);
        if (status == ACAMERA_OK && entry.count > 0) {
            int64_t exposureTime = entry.data.i64[0];
            __android_log_print(ANDROID_LOG_INFO, "NativeCamera", 
                               "📸 PHOTO Metadata - Exposure Time: %lld ns", (long long)exposureTime);
        }
    }
}

void NativeCameraManager::onPhotoCaptureFailed(void* context, ACameraCaptureSession* session,
                                              ACaptureRequest* request, ACameraCaptureFailure* failure) {
    (void)context;
    (void)session;
    (void)request;
    if (failure) {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", 
                           "📸 PHOTO Frame Failed - Reason: %d, Frame Number: %lld", 
                           failure->reason, (long long)failure->frameNumber);
    } else {
        __android_log_print(ANDROID_LOG_ERROR, "NativeCamera", "📸 PHOTO Frame Failed - Unknown reason");
    }
}